package com.yuanhua.sim.netty.serve;

import com.yuanhua.sim.netty.serve.handler.MyNettySocketChannelHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author yuanhua
 */
@ChannelHandler.Sharable
@Component
public class NettySocketServer {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workGroup = new NioEventLoopGroup();

    @Resource
    MyNettySocketChannelHandler myNettySocketChannelHandler;

    @Value("${server.simPort}")
    private int simPort;

    public void run(){
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workGroup)
                    //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数  还有几个选项没加，需要学习
                    .option(ChannelOption.SO_BACKLOG, 2048)
                    .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(512*1024, 1024*1024))
                    .channel(NioServerSocketChannel.class)
                    //添加日志处理器？或者切面
                    .childHandler(myNettySocketChannelHandler);
            System.out.println("客户端等待连接....");
            Channel ch = bootstrap.bind(simPort).sync().channel();
            ch.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //优雅的退出程序
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
